package com.atguigu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.customer.mapper.CustomerInfoMapper;
import com.atguigu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.atguigu.daijia.customer.service.CustomerInfoService;
import com.atguigu.daijia.model.entity.customer.CustomerInfo;
import com.atguigu.daijia.model.entity.customer.CustomerLoginLog;
import com.atguigu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.atguigu.daijia.model.vo.customer.CustomerLoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
@RequiredArgsConstructor
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    private final WxMaService wxMaService;

    private final CustomerInfoMapper customerInfoMapper;

    private final CustomerLoginLogMapper customerLoginLogMapper;

    /**
     * 用户登录
     *
     * @param code
     * @return
     */
    @Override
    public Long login(String code) {
        String openid = null;
        CustomerInfo customerInfo = null;
        try {
            //1.根据code查询openid
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
            //2.判断是否存在
            LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CustomerInfo::getWxOpenId,openid);
            customerInfo = customerInfoMapper.selectOne(wrapper);
            //3.不存在则加入用户表
            if(customerInfo == null){
                customerInfo = new CustomerInfo();
                customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
                customerInfo.setAvatarUrl("https://img.zcool.cn/community/01a3865ab91314a8012062e3c38ff6.png@1280w_1l_2o_100sh.png");
                customerInfo.setWxOpenId(openid);
                customerInfoMapper.insert(customerInfo);
            }
            //4.加入登录日志表
            CustomerLoginLog loginLog = new CustomerLoginLog();
            loginLog.setCustomerId(customerInfo.getId());
            loginLog.setMsg("微信登录");
            loginLog.setUpdateTime(new Date());
            customerLoginLogMapper.insert(loginLog);

        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //5.返回用户id
        return customerInfo.getId();
    }

    /**
     * 获取登录用户信息
     *
     * @param customerId
     * @return
     */
    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
        //1.根据id查询用户信息
        CustomerInfo customerInfo = getById(customerId);
        //2.封装vo
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo,customerLoginVo);
        customerLoginVo.setIsBindPhone(StringUtils.hasText(customerInfo.getPhone()));
        //3.返回
        return customerLoginVo;
    }

    /**
     * 更新用户微信手机号
     *
     * @param updateWxPhoneForm
     * @return
     */
    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        try {
            WxMaPhoneNumberInfo phoneNoInfo =
                    wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();
            CustomerInfo customerInfo =
                    customerInfoMapper.selectById(updateWxPhoneForm.getCustomerId());
            customerInfo.setPhone(phoneNumber);
            customerInfoMapper.updateById(customerInfo);
            return true;
        } catch (WxErrorException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
